import React from 'react';
import { Form, Input, Select, Button, Table, Modal } from 'antd';
import { fieldColumns } from './data';
import type { FieldDataType } from './data.d';

const { Option } = Select;

const ServerType = ({ modeler, currentElement }: any) => {
  const [serverForm] = Form.useForm();
  const [fieldForm] = Form.useForm();
  // 字段表格
  const [fieldTableData, setFieldTableData] = React.useState<FieldDataType[]>(
    [],
  );
  // 控制注入字段弹框
  const [isFieldModalOpen, setIsFieldModalOpen] = React.useState(false);
  const [filedEditKey, setFiledEditKey] = React.useState('');

  // 字段编辑
  const fieldEdit = (record: FieldDataType) => {
    let formData = {
      name: record.name,
      value: record.value,
    };
    setFiledEditKey(record.key);
    fieldForm.setFieldsValue(formData);
    setIsFieldModalOpen(true);
  };

  // 字段删除
  const fieldDel = (record: FieldDataType) => {
    let data = fieldTableData.filter((item) => {
      return item.key != record.key;
    });
    setFieldTableData(data);
  };

  // 自定义监听器表格操作行渲染
  const fieldActionRender: any = (
    text: any,
    record: FieldDataType,
    index: number,
  ) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <a onClick={() => fieldEdit(record)}>编辑</a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <a onClick={() => fieldDel(record)}>删除</a>
      </li>
    </ul>
  );

  // 自定义监听器表格渲染
  fieldColumns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = fieldActionRender) : undefined;
  });

  // 初始化
  React.useEffect(() => {
    let obj = {
      type: '',
      value: '',
    };
    for (const key in currentElement.businessObject) {
      switch (key) {
        case 'class':
          if (currentElement.businessObject[key]) {
            obj.type = key;
            obj.value = currentElement.businessObject[key];
          }
          break;
        case 'expression':
          if (currentElement.businessObject[key]) {
            obj.type = key;
            obj.value = currentElement.businessObject[key];
          }
          break;
        case 'delegateExpression':
          if (currentElement.businessObject[key]) {
            obj.type = key;
            obj.value = currentElement.businessObject[key];
          }
          break;
        default:
          break;
      }
    }
    serverForm.setFieldsValue(obj);
    let arr = currentElement.businessObject.extensionElements?.values
      .filter((item: any) => {
        return item.$type.indexOf('Field') != -1;
      })
      .map((item: any) => {
        let obj = {
          key: item.name + item.string?.body,
          name: item.name,
          value: item.string?.body,
        };
        return obj;
      });
    setFieldTableData(arr);
  }, [currentElement]);

  // 字段模态框确定按钮
  const handleFieldOk = async () => {
    const values = await fieldForm.validateFields();
    let obj: FieldDataType = {
      key: values.name + values.value,
      name: values.name,
      value: values.value,
    };
    let data: FieldDataType[];
    if (fieldTableData == undefined) {
      data = [];
    } else {
      data = [...fieldTableData];
    }
    if (filedEditKey != '') {
      data.filter((item, index) => {
        if (item.key == filedEditKey) {
          data[index] = obj;
        }
      });
    } else {
      data.push(obj);
    }
    setFiledEditKey('');
    setFieldTableData(data);
    fieldForm.resetFields();
    setIsFieldModalOpen(false);
  };

  // 注入字段模态框取消按钮
  const handleFieldCancel = () => {
    fieldForm.resetFields();
    setFiledEditKey('');
    setIsFieldModalOpen(false);
  };

  // 保存服务类型
  const saveServer = async () => {
    let data = await serverForm.getFieldsValue();
    let properties: any = {};
    properties[`flowable:class`] = '';
    properties[`flowable:expression`] = '';
    properties[`flowable:delegateExpression`] = '';
    properties[`flowable:${data.type}`] = data.value;
    updateProperties(properties);
    let extensionElements =
      currentElement.businessObject.get('extensionElements');
    if (!extensionElements) {
      extensionElements = modeler
        .get('moddle')
        .create('bpmn:ExtensionElements');
      currentElement.businessObject.extensionElements = extensionElements;
    }
    currentElement.businessObject.extensionElements.values = [];
    fieldTableData?.map((item) => {
      const field = modeler.get('moddle').create('flowable:Field');
      field.name = item.name;
      field['string'] = modeler.get('moddle').create(`flowable:string`);
      field['string'].body = item.value;
      currentElement.businessObject.extensionElements.values.push(field);
    });
  };

  /**
   * 更新元素属性
   * @param { Object } 要更新的属性, 例如 { name: '', id: '' }
   */
  const updateProperties = (properties: any) => {
    const modeling = modeler.get('modeling');
    modeling.updateProperties(currentElement, properties);
  };

  return (
    <>
      <Form form={serverForm}>
        <Form.Item name="type" label="服务类型">
          <Select placeholder="请选择服务类型">
            <Option value="class">类</Option>
            <Option value="expression">表达式</Option>
            <Option value="delegateExpression">委托表达式</Option>
          </Select>
        </Form.Item>
        <Form.Item name="value" label="服务值">
          <Input placeholder="请填写服务值" onBlur={saveServer} />
        </Form.Item>
      </Form>
      <Button type="primary" block onClick={() => setIsFieldModalOpen(true)}>
        注入字段
      </Button>
      <Table
        columns={fieldColumns}
        dataSource={fieldTableData}
        rowKey="key"
      ></Table>
      <Modal
        okText="确定"
        cancelText="取消"
        title="注入字段"
        open={isFieldModalOpen}
        onOk={handleFieldOk}
        onCancel={handleFieldCancel}
      >
        <Form form={fieldForm}>
          <Form.Item label="字段名称" name="name">
            <Input placeholder="请填写字段名称" />
          </Form.Item>
          <Form.Item label="字段" name="value">
            <Input placeholder="请填写字段值" />
          </Form.Item>
        </Form>
      </Modal>
      <Button onClick={saveServer} style={{ marginTop: 10 }} block>
        保存服务类型
      </Button>
    </>
  );
};

export default ServerType;
